//
//  LSZPersonalInformationVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2017/9/30.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZPersonalInformationVC.h"


#import <AssetsLibrary/AssetsLibrary.h>//判断拍照和相册是否授权

@interface LSZPersonalInformationVC ()<LDImagePickerDelegate,AddressViewDelegate>
@property(nonatomic,strong) NSMutableArray * recordSchooling;
@property(nonatomic,strong) NSMutableArray * professional;
@property (nonatomic, strong) YAddressPickerView *addView;

@end

@implementation LSZPersonalInformationVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic initWithGetUserInformation:^(BOOL isOK, NSString * str, LSZPersonalInformationManager * manager) {
        if (isOK == YES) {
            weakSelf.informationManager = manager;
            [weakSelf.tableViewMy reloadData];
            NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"yes" forKey:@"homePage"];
        }else{
            [weakSelf addHubPromptMessage:str];
        }
    }];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    _tableViewMy = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    _tableViewMy.dataSource = self;
    _tableViewMy.delegate = self;
    //添加以下代码关闭估算行高
    _tableViewMy.estimatedRowHeight = 0;
    _tableViewMy.estimatedSectionHeaderHeight = 0;
    _tableViewMy.estimatedSectionFooterHeight = 0;
    //如果没有占满则清除下面的
    _tableViewMy.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [_tableViewMy setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
    [self.view addSubview:_tableViewMy];
    self.arrayTitle = @[@"头像",@"昵称",@"性别",@"区域",@"生日",@"职业",@"教育经历",@"个人介绍",@"资质认证"];
    self.ArrayGender = [[NSMutableArray alloc]initWithObjects:@"男",@"女", nil];

    self.recordSchooling = [[NSMutableArray alloc]initWithObjects:@"初中以下",@"高中",@"专科",@"本科",@"硕士",@"博士及以上",@"其他", nil];
    self.professional = [[NSMutableArray alloc]initWithObjects:@"工人",@"农民",@"商人",@"上班族",@"公务员",@"家庭主妇",@"退休",@"其他", nil];
    _addView = [[YAddressPickerView alloc]init];
    [self.view addSubview:_addView];
   _addView.delegate = self;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (ScreenWidth == 320) {
            return 60;
        }else if(ScreenWidth == 375){
            return 65;
        }
        else {
            return 73;
        }
    }else{
        if (ScreenWidth == 320) {
            return 45;
        }else if(ScreenWidth == 375){
            return 50;
        }
        else {
            return 58;
        }
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayTitle.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZPersonalInformationMg * manager = nil;
    manager = self.informationManager.mutDataArray[0];
    if (indexPath.row == 0) {
        LSZInformationTableViewCell * cell = [[LSZInformationTableViewCell alloc]initWithStyleImageViewAndlabel:1];
        cell.labelTitle.text = [NSString stringWithFormat:@"%@",self.arrayTitle[indexPath.row]];
        cell.imageViewPhoto.hidden = NO;
        cell.labelName.hidden = YES;
        NSString * avatar = NullStringjudgment(manager.avatar);
        if([avatar isEqualToString:@""]){
            cell.imageViewPhoto.image = [UIImage imageNamed:@"placeholder"];
        }else{
            NSString * State = [[NSUserDefaults standardUserDefaults]objectForKey:@"headerPhoto"];
            [cell.imageViewPhoto sd_setImageWithURL:[NSURL URLWithString:State] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        LSZInformationTableViewCell * cell = [[LSZInformationTableViewCell alloc]initWithStyleImageViewAndlabel:2];
        cell.labelTitle.text = [NSString stringWithFormat:@"%@",self.arrayTitle[indexPath.row]];
        cell.imageViewPhoto.hidden = YES;
        cell.labelName.hidden = NO;
        if (indexPath.row == 1) {
            if(manager.username.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.username];
            }
        }
        if (indexPath.row == 2) {
            if(manager.gender.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.gender];
            }
        }
        if (indexPath.row == 3) {
            if(manager.location.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.location];
            }
        }
        if (indexPath.row == 4) {//生日
            if(manager.dob.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.dob];
            }
        }
        if (indexPath.row == 5) {//职业
            if(manager.occupation.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.occupation];
            }
        }
        if (indexPath.row == 6) {//教育
            if(manager.education.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.education];
            }
        }
        if (indexPath.row == 7) {//个人介绍
            if(manager.interests.length == 0){
                cell.labelName.text = @"未设置";
            }else{
                cell.labelName.text = [NSString stringWithFormat:@"%@",manager.interests];
            }
        }
        if (indexPath.row == 8) {//资质认证
            cell.labelName.hidden = YES;
//            if([manager.interests isEqualToString:@"2"]){
//                cell.labelName.text = [NSString stringWithFormat:@"已认证"];
//            }else{
//                cell.labelName.text = [NSString stringWithFormat:@"未认证"];
//            }
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
         //修改头像
        [self ModifyThePicture];
    }
    else if(indexPath.row == 1||indexPath.row == 7){
    //修改昵称
        LSZNicknameVC * VC = [[LSZNicknameVC alloc]init];
        VC.whereFrom = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        [self.navigationController pushViewController:VC animated:YES];
    }else if(indexPath.row == 8){
        LSZQualificationCertificationVC * VC = [[LSZQualificationCertificationVC alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    }
    else{
        [self SelectArea :indexPath.row];
    }
}
#pragma mark - 修改头像
-(void)ModifyThePicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *showAllInfoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneFromThePhotoAlbum];
    }];
    UIAlertAction *pickAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneTakingpictures];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [actionSheetController addAction:cancelAction];
    [actionSheetController addAction:pickAction];
    [actionSheetController addAction:showAllInfoAction];
    [weakSelf presentViewController:actionSheetController animated:YES completion:nil];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            [self initWithtring:@"摄像头访问受限,请打开摄像头允许拍摄!"];
            return;
        }
    }
    else {
        [self initWithtring:@"此设备没有摄像功能!"];
        return;
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:0   InViewController:self Scale:1];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:1   InViewController:self Scale:1];
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage{
    UIImage *imagestr = editedImage;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    if(result == YES ){
        //需要在此处上传服务器
        __weak typeof(self) weakSelf = self;
        [LSZRequestData initWithModifyThePicture:imagestr filePath:filePath :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            if(isOk == YES){
                NSString * urlStr = dic[@"data"];
                LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
                cell.imageViewPhoto.image = imagestr;
                [weakSelf LinkStorageOfImages:urlStr];
            }else{
                [weakSelf addHubPromptMessage:str];
            }
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *imagestr = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    if(result == YES ){
        //需要在此处上传服务器
         __weak typeof(self) weakSelf = self;
        [LSZRequestData initWithModifyThePicture:imagestr filePath:filePath :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            if(isOk == YES){
                NSString * urlStr = dic[@"data"];
                LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
                cell.imageViewPhoto.image = imagestr;
                [weakSelf LinkStorageOfImages:urlStr];
            }else{
                [weakSelf addHubPromptMessage:str];
            }
        }];
    }
}
#pragma mark - 把上传的图片的链接存储在本地
-(void)LinkStorageOfImages :(NSString *)url
{
    //    获取当前时间的毫秒数
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    NSString * date = [formatter stringFromDate:[NSDate date]];
    NSString * timeNow = [[NSString alloc] initWithFormat:@"%@", date];
    //八位随机数
    NSString * strRandom = @"";
    for (int i=0; i<3; i++) {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random() % 9)];
    }
    //   avatar 头像
    NSString * imageNameStr = [NSString stringWithFormat:@"%@?%@%@",url,timeNow,strRandom];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:imageNameStr forKey:@"headerPhoto"];
}
-(void)chooseArea
{
      [_addView show];
}
#pragma mark - 地区选择完毕
- (void)completingTheSelection:(NSString *)province city:(NSString *)city area:(NSString *)area{
    __weak typeof(self) weakSelf = self;
    NSString * str = [[NSString alloc]init];
    if ([province isEqualToString:city]) {
        str =  [NSString stringWithFormat:@"%@ %@",province,area];
    }else{
        str =  [NSString stringWithFormat:@"%@ %@ %@",province,city,area];
    }
    LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3  inSection:0]];
    cell.labelName.text = [NSString stringWithFormat:@"%@",str];
    [weakSelf SetGenderOrArea:@"location" inputParameter:str];
}
#pragma mark - 选择生日
-(void)chooseBirthday
{
    __weak typeof(self) weakSelf = self;
    [UICustomDatePicker showCustomDatePickerAtView:self.view choosedDateBlock:^(NSDate *date) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [dateFormatter stringFromDate:date];
        LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4  inSection:0]];
        cell.labelName.text = [NSString stringWithFormat:@"%@",strDate];
        [weakSelf SetGenderOrArea:@"dob" inputParameter:strDate];
    } cancelBlock:^{

    }];
}
#pragma mark - 选择区域
-(void)SelectArea :(NSInteger)indexPathRow
{
    if (indexPathRow == 3) {
        [self chooseArea];//选择地区
    }else if(indexPathRow == 4){
        [self chooseBirthday];
    }
    else{
        [self chooseSingleOption:indexPathRow];
    }
}
-(void)chooseSingleOption :(NSInteger)indexPathRow
{
    __weak typeof(self) weakSelf = self;
    NSMutableArray * ArrayData = [[NSMutableArray alloc]init];
    if (indexPathRow == 2) {
        ArrayData = weakSelf.ArrayGender;
    }
    else if(indexPathRow == 6){
        ArrayData = weakSelf.recordSchooling;
    }
    else {
        ArrayData = weakSelf.professional;
    }
    DLPickerView *pickerView = [[DLPickerView alloc] initWithDataSource:ArrayData withSelectedItem:nil withSelectedBlock:^(id selectedItem){
        if (indexPathRow == 2) {
            LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2  inSection:0]];
            cell.labelName.text = [NSString stringWithFormat:@"%@",selectedItem];
            if ([selectedItem isEqualToString:@"女"]) {
                [weakSelf SetGenderOrArea:@"gender" inputParameter:@"2"];
            }else{
                [weakSelf SetGenderOrArea:@"gender" inputParameter:@"1"];
            }
        }
        if (indexPathRow == 6) {
            LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6  inSection:0]];
            cell.labelName.text = [NSString stringWithFormat:@"%@",selectedItem];
          [weakSelf SetGenderOrArea:@"education" inputParameter:selectedItem];
        }
        if (indexPathRow == 5) {
            LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5  inSection:0]];
            cell.labelName.text = [NSString stringWithFormat:@"%@",selectedItem];
            [weakSelf SetGenderOrArea:@"occupation" inputParameter:selectedItem];
        }
    }];
    [pickerView show];
}
#pragma mark - 设置性别或者区域
-(void)SetGenderOrArea :(NSString *)input inputParameter:(NSString *)inputParameter
{
    __weak typeof(self) weakSelf = self;
    [LSZRequestData ChangeGenderAndArea:input inputParameter:inputParameter :^(BOOL isOK, NSString * Str, NSDictionary * dic) {
        [weakSelf initWithtring:Str];
    }];
}
@end
